from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Body, Form
from sqlalchemy.orm import Session
from .. import models, schemas
from ..crud import avatar as avatar_crud
from ..database import get_db
from ..deps import get_current_user
from ..utils.files import save_upload_file, APPEARANCE_DIR, VOICE_DIR
from ..api import starter_agent
import json

router = APIRouter()

@router.post("/starter/chat", response_model=schemas.ChatResponse)
async def chat_with_starter_agent(
    message: str = Body(..., embed=True),
    current_user: models.User = Depends(get_current_user)
):
    """与starter助手对话"""
    try:
        response = await starter_agent.chat_with_starter(message)
        return schemas.ChatResponse(
            message=response
        )
    except Exception as e:
        print(f"Chat route error: {str(e)}")  # 添加错误日志
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/create", response_model=schemas.Avatar)
async def create_avatar(
    prompt_settings: str = Form(...),
    appearance: UploadFile = File(...),
    voice: UploadFile = File(...),
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建用户化身"""
    try:
        # 解析 prompt_settings 字符串为字典
        try:
            prompt_settings_dict = json.loads(prompt_settings)
        except json.JSONDecodeError as e:
            raise HTTPException(status_code=422, detail=f"Invalid JSON format in prompt_settings: {str(e)}")
        
        # 添加用户名到 prompt_settings
        prompt_settings_dict["username"] = current_user.username
        
        # 检查必需字段
        required_fields = ["username", "personality", "interests", "values", "speaking_style", "sample_dialogue"]
        missing_fields = [field for field in required_fields if field not in prompt_settings_dict]
        if missing_fields:
            raise HTTPException(
                status_code=400,
                detail=f"化身配置缺少必需字段: {', '.join(missing_fields)}"
            )
        
        # 保存外观和声音文件
        appearance_path = await save_upload_file(appearance, APPEARANCE_DIR)
        voice_path = await save_upload_file(voice, VOICE_DIR)
        
        # 创建化身数据
        avatar_data = schemas.AvatarCreate(
            prompt_settings=prompt_settings_dict,
            appearance_image=appearance_path,
            voice_sample=voice_path
        )
        
        # 创建化身并关联到当前用户
        return avatar_crud.create_avatar(db, avatar_data, current_user.id)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/me", response_model=schemas.Avatar)
async def get_my_avatar(
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的化身"""
    avatar = avatar_crud.get_user_avatar(db, current_user.id)
    if not avatar:
        raise HTTPException(status_code=404, detail="您还没有创建化身")
    return avatar

@router.put("/me", response_model=schemas.Avatar)
async def update_my_avatar(
    prompt_settings: dict = Body(None),
    appearance: UploadFile = File(None),
    voice: UploadFile = File(None),
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新当前用户的化身"""
    try:
        # 获取现有化身
        avatar = avatar_crud.get_user_avatar(db, current_user.id)
        if not avatar:
            raise HTTPException(status_code=404, detail="您还没有创建化身")
            
        # 更新文件(如果提供)
        update_data = {}
        if appearance:
            appearance_path = await save_upload_file(appearance, APPEARANCE_DIR)
            update_data["appearance_image"] = appearance_path
        if voice:
            voice_path = await save_upload_file(voice, VOICE_DIR)
            update_data["voice_sample"] = voice_path
        if prompt_settings:
            update_data["prompt_settings"] = prompt_settings
            
        # 更新化身
        return avatar_crud.update_avatar(db, avatar.id, schemas.AvatarUpdate(**update_data))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{avatar_id}", response_model=schemas.Avatar)
async def get_avatar(avatar_id: str, db: Session = Depends(get_db)):
    """获取化身详情"""
    avatar = avatar_crud.get_avatar(db, avatar_id)
    if avatar is None:
        raise HTTPException(status_code=404, detail="化身不存在")
    return avatar

@router.put("/{avatar_id}", response_model=schemas.Avatar)
async def update_avatar(
    avatar_id: str,
    avatar: schemas.AvatarUpdate,
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新化身信息"""
    return avatar_crud.update_avatar(db, avatar_id, avatar, current_user.id) 